package com.jzo2o.xxl.job.config;

import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.xxl.job.properties.XxlJobProperties;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * XXL-Job 执行器配置类
 * 功能：初始化XXL-Job执行器，关联调度中心并加载执行器配置
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "xxl-job", value = "enable", havingValue = "true") // 启动 当xxl-job.enable=true时生效
@EnableConfigurationProperties(XxlJobProperties.class) // 引入配置类
public class XxlJobConfiguration {

    /**
     * 注册XXL-Job Spring执行器（核心组件）
     * 作用：连接调度中心，接收并执行分布式任务
     * @param prop 自动注入的XXL-Job配置属性
     * @return 初始化完成的XXL-Job执行器
     */
    @Bean
    public XxlJobSpringExecutor xxlJobExecutor(XxlJobProperties prop) {
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        XxlJobProperties.Admin admin = prop.getAdmin();
        if (admin != null && StringUtils.isNotEmpty(admin.getAddress())) {
            xxlJobSpringExecutor.setAdminAddresses(admin.getAddress());
        }
        XxlJobProperties.Executor executor = prop.getExecutor();
        xxlJobSpringExecutor.setAccessToken(prop.getAccessToken());
        if (executor != null) {
            xxlJobSpringExecutor.setIp(executor.getIp());
            xxlJobSpringExecutor.setAppname(executor.getAppName());
            xxlJobSpringExecutor.setPort(executor.getPort());
            xxlJobSpringExecutor.setLogPath(executor.getLogPath());
            xxlJobSpringExecutor.setLogRetentionDays(
                    executor.getLogRetentionDays()
            );
        }

        log.info(">>>>>>>>>>> xxl-job config end.");
        return xxlJobSpringExecutor;
    }
}
